package com.lnj.community.controller;

import com.lnj.community.dao.entity.*;
import com.lnj.community.dao.vo.CommentVo;
import com.lnj.community.dao.vo.ReplyVo;
import com.lnj.community.event.EventProduct;
import com.lnj.community.service.CommentService;
import com.lnj.community.service.DiscussPostService;
import com.lnj.community.service.LikeService;
import com.lnj.community.service.UserService;
import com.lnj.community.utiles.CommunityConstant;
import com.lnj.community.utiles.CommunityUtil;
import com.lnj.community.utiles.HostHolder;
import com.lnj.community.utiles.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

import static com.lnj.community.utiles.CommunityConstant.*;

@Controller
@RequestMapping("/discuss")
public class DiscussPostController {
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private UserService userService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private LikeService likeService;
    @Autowired
    private EventProduct eventProducer;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(path = "/add", method = RequestMethod.POST)
    @ResponseBody
    public String addDiscussPost(String title, String content) {
        User user= HostHolder.getUser();
        if (user == null) {
            return CommunityUtil.getJSONString(403, "你还没有登录!");
        }
        // 创建帖子对象
        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setTitle(title);
        post.setContent(content);
        post.setCreateTime(new Date());
        // 插入帖子
        discussPostService.addDiscussPost(post);

        //触发发帖事件 把帖子插入到Elasticsearch中 异步处理
        Event event=new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(user.getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(post.getId())
                .setEntityUserId(post.getUserId());

        eventProducer.fireEvent(event);

        // 计算帖子分数 先把帖子的id存到Redis中 然后在定时任务中计算分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey, post.getId());

        // 报错的情况,将来统一处理.
        return CommunityUtil.getJSONString(0, "发布成功!");
    }

    @RequestMapping(path = "/detail/{discussPostId}", method = RequestMethod.GET)
    public String getDiscussPost(@PathVariable("discussPostId") int discussPostId, Model model,Page page) {
        // 查询帖子
        DiscussPost post = discussPostService.findDiscussPostById(discussPostId);
        model.addAttribute("post", post);
        //查作者
        User user = userService.findUserById(post.getUserId());
        model.addAttribute("user", user);
        //查点赞数量
        long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeCount", likeCount);
        //查点赞状态
        int likeStatus = HostHolder.getUser() == null ? 0 :
                likeService.findEntityLikeStatus(HostHolder.getUser().getId(), ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeStatus", likeStatus);
        //查评论
        page.setLimit(5);
        page.setPath("/discuss/detail/" + discussPostId);
        page.setRows(post.getCommentCount());
        //评论:给帖子的评论
        //回复:给评论的评论
        List<Comment> comments = commentService.findCommentsByEntity(ENTITY_TYPE_POST,
                post.getId(), page.getOffset(), page.getLimit());

        //数据处理 评论的VO列表
        List<CommentVo> commentVoList=new ArrayList<>();
        if(comments!=null){
            for(Comment comment:comments){
                //评论的VO
                CommentVo commentVo=new CommentVo();
                //Map<String,Object> commentVo=new HashMap<>();
                //评论
                commentVo.setComment(comment);
                //评论的作者
                commentVo.setUser(userService.findUserById(comment.getUserId()));
                //评论的点赞
                likeCount = likeService.findEntityLikeCount(CommunityConstant.ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.setLikeCount(likeCount);
                //评论的点赞状态
                likeStatus = HostHolder.getUser() == null? 0 :
                        likeService.findEntityLikeStatus(HostHolder.getUser().getId(), CommunityConstant.ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.setLikeStatus(likeStatus);
                //回复
                List<Comment> replylist = commentService.findCommentsByEntity(CommunityConstant.ENTITY_TYPE_COMMENT, comment.getId(),
                        0, Integer.MAX_VALUE);
                //回复的VO列表
                List<ReplyVo> replyVoList=new ArrayList<>();
                if (replylist!=null){
                    for(Comment reply:replylist){
                        ReplyVo replyVo=new ReplyVo();
                       // Map<String,Object> replyVo=new HashMap<>();
                        //回复
                        replyVo.setReply(reply);
                        //回复的作者
                        replyVo.setUser(userService.findUserById(reply.getUserId()));
                        //回复的点赞
                        likeCount = likeService.findEntityLikeCount(CommunityConstant.ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.setLikeCount(likeCount);
                        //回复的点赞状态 当前用户的点赞状态
                        likeStatus = HostHolder.getUser() == null? 0 :
                                likeService.findEntityLikeStatus(HostHolder.getUser().getId(), CommunityConstant.ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.setLikeStatus(likeStatus);
                        //回复的目标
                        User user1 = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());
                        replyVo.setTarget(user1);
                        replyVoList.add(replyVo);
                    }
                }
                commentVo.setReplys(replyVoList);
                //回复的数量
                int replyCount = commentService.findCommentCount(CommunityConstant.ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.setReplyCount(replyCount);
                commentVoList.add(commentVo);
            }
        }
        model.addAttribute("comments",commentVoList);

        return "/site/discuss-detail";
    }


    // 置顶
    @RequestMapping(path = "/top", method = RequestMethod.POST)
    @ResponseBody
    public String setTop(int id) {
        discussPostService.updateType(id, 1);

        // 触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(HostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);

        return CommunityUtil.getJSONString(0);
    }

    // 加精
    @RequestMapping(path = "/wonderful", method = RequestMethod.POST)
    @ResponseBody
    public String setWonderful(int id) {
        discussPostService.updateStatus(id, 1);

        // 触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(HostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);

        // 计算帖子分数 先把帖子的id存到Redis中 然后在定时任务中计算分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey, id);

        return CommunityUtil.getJSONString(0);
    }

    // 删除
    @RequestMapping(path = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String setDelete(int id) {
        discussPostService.updateStatus(id, 2);

        // 触发删帖事件
        Event event = new Event()
                .setTopic(TOPIC_DELETE)
                .setUserId(HostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);

        return CommunityUtil.getJSONString(0);
    }

    //获取用户的帖子
    @RequestMapping(path = "/myPost/{userId}", method = RequestMethod.GET)
    public String getMyPost(@PathVariable("userId") int userId, Model model, Page page) {
        // 设置分页信息
        page.setLimit(5);
        page.setPath("/discuss/myPost/" + userId);
        page.setRows(discussPostService.findDiscussPostRows(userId));
        // 帖子列表
        List<DiscussPost> discussPosts = discussPostService.findDiscussPosts(userId, page.getOffset(), page.getLimit(), 0);
        List<Map<String, Object>> discussVoList = new ArrayList<>();
        if (discussPosts != null) {
            for (DiscussPost post : discussPosts) {
                Map<String, Object> map = new HashMap<>();
                // 帖子
                map.put("post", post);
                //点赞数量
                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                map.put("likeCount", likeCount);
                discussVoList.add(map);
            }
            model.addAttribute("discussPosts", discussVoList);
            model.addAttribute("discussPostCount", discussPosts.size());
        }

        return "/site/my-post";
    }
}
